package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.interfaces.BVehicleTypeService;
import cn.huiyunche.base.service.mappers.DFuelTypeMapper;
import cn.huiyunche.base.service.model.DFuelPriceEffective;
import cn.huiyunche.base.service.model.DFuelType;
import cn.huiyunche.base.service.model.DFuelTypeExample;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.driver.service.DFuelPriceEffectiveService;
import cn.huiyunche.driver.service.DFuelTypeService;
import cn.huiyunche.driver.service.form.DFuelTypeForm;
import cn.huiyunche.driver.service.query.DFuelTypeQueryConditions;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: cn.huiyunche.driver.service.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2017/2/26 下午5:31
 */
@Service
public class DFuelTypeServiceImpl implements DFuelTypeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DFuelTypeServiceImpl.class);

    @Autowired
    private DFuelTypeMapper dFuelTypeMapper;

    @Autowired
    private BVehicleTypeService bVehicleTypeService;

    @Autowired
    private DFuelPriceEffectiveService dFuelPriceEffectiveService;

    @Override
    public Integer add(DFuelTypeForm form, BindingResult br) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.add params : {}", form);

        if (null == form) {
            LOGGER.error("DFuelTypeServiceImpl.add param form must not be null");
            throw new IllegalArgumentException("燃油类型表单不能为空");
        }

        //验证表单
        verificationForm(br);

        /**
         * 判断燃油编码是否唯一
         */
        this.verificationCodeOrNameUnique(form.getId(), form.getFuelName(), form.getFuelCode());

        DFuelType fuelType = new DFuelType();
        BeanUtils.copyProperties(form, fuelType);

        dFuelTypeMapper.insertSelective(fuelType);

        return fuelType.getId();
    }

    @Override
    public DFuelType selectByPrimaryKey(Integer id) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.selectByPrimaryKey param : {}", id);

        if (null == id) {
            LOGGER.error("DFuelTypeServiceImpl.selectByPrimaryKey param id must not be null");
            throw new IllegalArgumentException("主键不能为空");
        }

        return dFuelTypeMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer update(DFuelTypeForm form, BindingResult br) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.update params : {}", form);

        if (null == form) {
            LOGGER.error("DFuelTypeServiceImpl.update params form must not be null");
            throw new IllegalArgumentException("燃油类型表单不能为空");
        }

        //验证表单
        verificationForm(br);

        /**
         * 判断燃油编码是否唯一
         */
        this.verificationCodeOrNameUnique(form.getId(), form.getFuelCode(), form.getFuelName());

        DFuelType fuelType = new DFuelType();
        BeanUtils.copyProperties(form, fuelType);

        dFuelTypeMapper.updateByPrimaryKeySelective(fuelType);

        return fuelType.getId();
    }

    private void verificationForm(BindingResult br) {

        if (null == br) {
            LOGGER.error("DFuelTypeServiceImpl.verificationForm error br is null");
            throw new IllegalArgumentException("BindingResult is null");
        }

        if (br.hasErrors()) {
            List<ObjectError> list = br.getAllErrors();
            LOGGER.error("DRouteServiceImpl.add error : {}", list.get(0).getDefaultMessage());
            throw new IllegalArgumentException(list.get(0).getDefaultMessage());
        }
    }

    @Override
    public void delete(Integer id) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.delete param : {}", id);

        if (null == id || 0 == id.intValue()) {
            LOGGER.error("DFuelTypeServiceImpl.delete error id must not be null");
            throw new IllegalArgumentException("主键不能为空");
        }

        /**
         * 查询燃油类型是否跟燃油价格变动关联
         */
        List<DFuelPriceEffective> fuelPriceEffectives = dFuelPriceEffectiveService.selectByFuelTypeId(id);
        if (CollectionUtils.isNotEmpty(fuelPriceEffectives)) {
            LOGGER.error("DFuelTypeServiceImpl.delete error fuelPriceEffectives is not empty ");
            throw new BusinessException("请先解除燃油类型和燃油价格变动的关联！");
        }

        dFuelTypeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> selectListByConditions(PageVo pageVo, DFuelTypeQueryConditions conditions) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.selectListByConditions params : {}, {}", pageVo, conditions);

        if (null == pageVo) {
            LOGGER.error("DFuelTypeServiceImpl.selectListByConditions param pageVo must not be null");
            throw new IllegalArgumentException("分页信息不能为空");
        }
        if (null == conditions) {
            LOGGER.error("DFuelTypeServiceImpl.selectListByConditions param conditions must not be null");
            throw new IllegalArgumentException("查询条件信息不能为空");
        }

        Map<String, Object> map = new HashMap<>();
        String orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " update_time DESC";

        DFuelTypeExample example = new DFuelTypeExample();
        DFuelTypeExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(conditions.getFuelCode())) {
            criteria.andFuelCodeLikeInsensitive("%" + conditions.getFuelCode() + "%");
        }
        if (StringUtils.isNotBlank(conditions.getFuelName())) {
            criteria.andFuelNameLikeInsensitive("%" + conditions.getFuelName() + "%");
        }

        pageVo.setTotalRecord(dFuelTypeMapper.countByExample(example));
        example.setLimitStart(pageVo.getStartIndex());
        example.setLimitEnd(pageVo.getPageSize());
        example.setOrderByClause(orderByClause);

        List<DFuelType> list = dFuelTypeMapper.selectByExample(example);
        map.put("page", pageVo);
        map.put("list", list);

        return map;
    }

    @Override
    public List<DFuelType> selectListByConditions(DFuelTypeQueryConditions conditions) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.selectListByConditions params : {}", conditions);

        DFuelTypeExample example = new DFuelTypeExample();
        DFuelTypeExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(conditions.getFuelCode())) {
            criteria.andFuelCodeLikeInsensitive("%" + conditions.getFuelCode() + "%");
        }
        if (StringUtils.isNotBlank(conditions.getFuelName())) {
            criteria.andFuelNameLikeInsensitive("%" + conditions.getFuelName() + "%");
        }

        return dFuelTypeMapper.selectByExample(example);
    }

    @Override
    public void verificationCodeOrNameUnique(Integer id, String fuelName, String fuelCode) throws Exception {
        LOGGER.info("DFuelTypeServiceImpl.verificationCodeOrNameUnique params : {}, {}", fuelCode, fuelName);

        if (StringUtils.isBlank(fuelCode)) {
            LOGGER.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique param fuelCode must not be null");
            throw new IllegalArgumentException("燃油类型编码不能为空");
        }
        if (StringUtils.isBlank(fuelName)) {
            LOGGER.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique param fuelName must not be null");
            throw new IllegalArgumentException("燃油类型名称不能为空");
        }

        DFuelTypeExample example = new DFuelTypeExample();
        example.createCriteria().andFuelCodeEqualTo(fuelCode);

        List<DFuelType> list = dFuelTypeMapper.selectByExample(example);


        if (CollectionUtils.isNotEmpty(list)) {

            DFuelType fuelType = list.get(0);

            if (id != null && id == fuelType.getId()) {
                return;
            }
            LOGGER.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique error list is not empty");
            throw new BusinessException("燃油编码已存在！");
        }

        DFuelTypeExample example1 = new DFuelTypeExample();
        example1.createCriteria().andFuelNameEqualTo(fuelName);

        list = dFuelTypeMapper.selectByExample(example1);

        if (CollectionUtils.isNotEmpty(list)) {

            DFuelType fuelType1 = list.get(0);

            if (id != null && id == fuelType1.getId()) {
               return;
            }
            LOGGER.error("DFuelTypeServiceImpl.verificationCodeOrNameUnique error list is not empty");
            throw new BusinessException("燃油名称已存在！");
        }
    }

}
